﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace RSA文件加密
{
    public class RSA2
    {
        private RSACryptoServiceProvider rsa;
        public RSA2()
        {
            rsa = new RSACryptoServiceProvider();
        }

        public string GetPublicKey()
        {
            return rsa.ToXmlString(false);
        }

        public string GetPrivateKey()
        {
            return rsa.ToXmlString(true);
        }

        /// <summary>
        /// 加密文件
        /// </summary>
        /// <param name="inFileName">待加密文件路径</param>
        /// <param name="outFileName">加密后文件路径</param>
        /// <param name="PublicKey">公钥</param>
        public void Encrypt(string inFileName, string outFileName, string PublicKey)
        {
            rsa.FromXmlString(PublicKey);
            FileStream fin = new FileStream(inFileName, FileMode.Open, FileAccess.Read);
            FileStream fout = new FileStream(outFileName, FileMode.OpenOrCreate, FileAccess.Write);
            fout.SetLength(0);

            byte[] bin = new byte[117];
            long rdlen = 0;
            long totlen = fin.Length;
            int len;

            while (rdlen < totlen)
            {
                len = fin.Read(bin, 0, 117);
                byte[] bout = rsa.Encrypt(bin, false);
                fout.Write(bout, 0, bout.Length);
                rdlen = rdlen + len;
            }

            fout.Close();
            fin.Close();

        }

        /// <summary>
        /// 解密文件
        /// </summary>
        /// <param name="inFileName">待解密文件路径</param>
        /// <param name="outFileName">解密后文件路径</param>
        /// <param name="PrivateKey">私钥</param>
        public void Decrypt(string inFileName, string outFileName, string PrivateKey)
        {
          
                rsa.FromXmlString(PrivateKey);
                FileStream fin = new FileStream(inFileName, FileMode.Open, FileAccess.Read);
                FileStream fout = new FileStream(outFileName, FileMode.OpenOrCreate, FileAccess.Write);
                fout.SetLength(0);

                byte[] bin = new byte[128];
                long rdlen = 0;
                long totlen = fin.Length;
                int len;
                try
                {
                    while (rdlen < totlen)
                    {
                        len = fin.Read(bin, 0, 128);
                        byte[] bout = rsa.Decrypt(bin, false);
                        fout.Write(bout, 0, bout.Length);
                        rdlen = rdlen + len;
                    }
                    fout.Close();
                    fin.Close();

                }
                catch
                {
                    fout.Close();
                    fin.Close();
                }
           

        }

    }
}
